package com.example.tangjiangxu.powerimageview;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Movie;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.widget.ImageView;

import java.io.InputStream;
import java.lang.reflect.Field;

/**
 * Created by tangjiangxu on 4/11/17.
 */

public class PowerImageView extends ImageView implements View.OnClickListener {
    private static final String TAG = "PowerImageView";
    /** 播放GIF动画的关键类 **/
    private Movie mMovie;
    private Bitmap mStartButton;
    /** 动画开始时间 **/
    private long mMobieStart;
    /** 图片的宽高 **/
    private int mImageWidth;
    private int mImageHeight;
    /** 图片是否正在播放 **/
    private boolean isPlaying;
    /** 是否允许自动播放 **/
    private boolean isAutoPlay;

    private PowerImageView(Context context) {
        super(context);
    }

    public PowerImageView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    /**
     * PowerImageView构造函数，在这里完成所有必要的初始化操作
     * @param context
     * @param attrs
     * @param defStyle
     */
    public PowerImageView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        try {
            TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.PowerImageView);
            int resourceId = getResourceId(a, context, attrs);
            if (resourceId != 0) {
                //当资源id不等于0，就去获取该资源的流
                InputStream is = getResources().openRawResource(resourceId);
                //使用Movie类对流进行解码
                mMovie = Movie.decodeStream(is);
                if (mMovie != null) {
                    //如果返回值不等于null,就说明这是一个GIF图片，下面获取是否自动播放的属性
                    isAutoPlay = a.getBoolean(R.styleable.PowerImageView_auto_play, false);
                    Bitmap bitmap = BitmapFactory.decodeStream(is);
                    mImageHeight = bitmap.getHeight();
                    mImageWidth = bitmap.getWidth();
                    bitmap.recycle();
                    if (!isAutoPlay) {
                        //当不允许自动播放的时候，得到开始播放按钮的图片，并注册点击事件
                        mStartButton = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
                        setOnClickListener(this);
                    }
                }
            }
            if (a != null) {
                a.recycle();
            }
            Log.e(TAG, "PowerImageView: 结束");
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    /**
     * 通过Java 反射，获取src指定图片资源所对应的id
     * @param a
     * @param context
     * @param attrs
     * @return 通过布局文件中指定图片资源所对应的ID，没有指定任何图片资源就返回0
     */
    private int getResourceId(TypedArray a, Context context, AttributeSet attrs) {
        try {
            Field field = TypedArray.class.getDeclaredField("mValue");
            field.setAccessible(true);
            TypedValue typedValueObject = (TypedValue) field.get(a);
            return typedValueObject.resourceId;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return 0;
    }


    @Override
    protected void onDraw(Canvas canvas) {
        Log.e(TAG, "onDraw: ");
        if (mMovie == null) {
            //mMovie为null，说明是图片图片，则直接调用父类的onDraw方法
            super.onDraw(canvas);
        } else {
            if (isAutoPlay) {
                playMovie(canvas);
                invalidate();
            } else {
                //不允许自动播放时，判断当前图片是否正在播放
                if (isPlaying) {
                    //正在播放就继续调用playMovie方法，一只到动画播放结束为止
                    if (playMovie(canvas)) {
                        isPlaying = false;
                    }
                    invalidate();
                } else {
                    //如果还没开始播放，就只绘制GIF图片的第一张，并绘制一个开始按钮
                    mMovie.setTime(0);
                    mMovie.draw(canvas, 0, 0);
                    int offsetW = (mImageWidth - mStartButton.getWidth()) / 2;
                    int offsetH = (mImageHeight - mStartButton.getHeight()) / 2;
                    canvas.drawBitmap(mStartButton, offsetW, offsetH, null);
                }

            }
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        Log.e(TAG, "onMeasure: ");
        if (mMovie != null) {
            //如果GIF图片，则重写，设定PowerImageView的大小
            setMeasuredDimension(mImageWidth, mImageHeight);
        }
    }

    /**
     * 开始播放GIF动画，播放完成返回true，未完成返回false
     * @param canvas
     * @return
     */
    private boolean playMovie(Canvas canvas) {
        Log.e(TAG, "playMovie: " );
        long now = SystemClock.uptimeMillis();
        if (mMobieStart == 0) {
            mMobieStart = now;
        }
        int duration = mMovie.duration();
        Log.e(TAG, "playMovie: duration:"  + duration);
        if (duration == 0) {
            duration = 1000;
        }
        int relTime = (int) ((now - mMobieStart) % duration);
        Log.e(TAG, "playMovie: relTime:"  + relTime);
        mMovie.setTime(relTime);
        mMovie.draw(canvas, 0, 0);
        if ((now - mMobieStart) >= duration) {
            mMobieStart = 0;
            return true;
        }
        return false;
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == getId()) {
            //当用户点击图片时，开始播放gif动画
            isPlaying = true;
            invalidate();
        }
    }



}
